import * as vscode from 'vscode';
import {CommandItem} from './CommandItem';

export class ExtensionCommandsProvider implements vscode.TreeDataProvider<CommandItem> {

	constructor(private context: vscode.ExtensionContext) { }

	getTreeItem(element: CommandItem): vscode.TreeItem {
		return element;
	}

	async getChildren(element?: CommandItem): Promise<CommandItem[]> {
		try {
			if (element) {
				return []; // 没有子项
			}

			const extension = vscode.extensions.getExtension(this.context.extension.id);
			if (!extension) {
				vscode.window.showErrorMessage('无法获取扩展信息');
				return [];
			}

			const packageJSON = extension.packageJSON;
			const contributedCommands = packageJSON.contributes?.commands || [];

			return contributedCommands.map((cmd: any) => {
				const item = new CommandItem(
					cmd.command,
					cmd.title || cmd.command,
					vscode.TreeItemCollapsibleState.None
				);

				item.command = {
					command: 'vscodeTextUtil.executeCommand',
					title: 'Execute Command',
					arguments: [cmd.command]
				};

				return item;
			});

		} catch (error) {
			vscode.window.showErrorMessage(`获取命令列表失败: ${error}`);
			return [];
		}
	}
}